package in.srain.cube.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {

    final static int BUFFER_SIZE = 2048;

    public static void zipFile(File srcFile, File destFile) {
        try {
            BufferedInputStream origin;
            FileOutputStream destStream = new FileOutputStream(destFile);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(destStream));
            if (srcFile.isDirectory()) {
                zipFolders(out, srcFile, srcFile.toURI());
            } else {
                byte data[] = new byte[BUFFER_SIZE];
                FileInputStream fi = new FileInputStream(srcFile);
                origin = new BufferedInputStream(fi, BUFFER_SIZE);
                ZipEntry entry = new ZipEntry(srcFile.getName());
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
                    out.write(data, 0, count);
                }
            }
            out.close();
        } catch (Exception e) {
        }
    }

    private static void zipFolders(ZipOutputStream out, File folder, URI root) throws IOException {
        File[] fileList = folder.listFiles();
        BufferedInputStream origin;
        int count;
        byte data[] = new byte[BUFFER_SIZE];
        for (File fileItem : fileList) {
            if (fileItem.isDirectory()) {
                zipFolders(out, fileItem, root);
            } else {
                String relativePath = root.relativize(fileItem.toURI()).getPath();
                FileInputStream fi = new FileInputStream(fileItem);
                origin = new BufferedInputStream(fi, BUFFER_SIZE);
                ZipEntry entry = new ZipEntry(relativePath);
                out.putNextEntry(entry);
                while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }
        }
    }
}
